package com.example.redis.util;

import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

@Service
public class LockReExpire {


    @Autowired
    private RedisTemplate redisTemplate;

    public void reExpire(HashedWheelTimer timer) {
        timer.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                Boolean flag = (Boolean) redisTemplate.execute(RedisScript.of("if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
                        "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                        "return 1; " +
                        "end; " +
                        "return 0;", Boolean.class), Arrays.asList("key"), 30);
                if (flag) {
                    reExpire(timer);
                } else {
                    System.out.println("续期结束！");
                }
            }
        }, 10, TimeUnit.SECONDS);
    }

    public static void main(String[] args) {
        HashedWheelTimer timer = new HashedWheelTimer();
        renew(timer);
    }

    public static void renew(HashedWheelTimer timer) {
        Timeout timeout = timer.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                LocalDateTime targetDateTime = LocalDateTime.parse("2023-11-11 22:24:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                LocalDateTime currentDateTime = LocalDateTime.now();

                if (currentDateTime.isAfter(targetDateTime)) {
                    System.out.println("续期结束");
                    timeout.cancel();
                } else {
                    System.out.println("续期！");
                    renew(timer);
                }
            }
        }, 10, TimeUnit.SECONDS);
    }
}
